package disk;

import group.GeoGroup;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;

import node.GeoNode;

import component.AbstractComponent;
import component.Ball;
import component.Structure;
import component.Tube;

public class Save {
	private DataOutputStream out;
	private GeoGroup group;
	
	public Save(Structure structure) {
		group = structure.getPermanentGeoGroup();
	}
	
	public void save() throws IOException {
		File file = chooseFile();
		if (file == null) return;
		saveToFile(file);
	}
	
	private File chooseFile() {
		final JFileChooser fc = new JFileChooser();
		int returnVal = fc.showSaveDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			return fc.getSelectedFile();
		}
		return null;
	}
	
	private void saveToFile(File file) throws IOException {
		out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
		writeGroup();
		out.close();
	}
	
	private void writeGroup() throws IOException {
		for (GeoNode node : group.getGeoNodes()) {
			writeComponent(node.getComponent());
		}
	}
	private void writeComponent(AbstractComponent component) throws IOException {
		if (component instanceof Ball) {
			writeBall((Ball)component);
		} else if (component instanceof Tube) {
			writeTube((Tube)component);
		}
	}

	private void writeTube(Tube component) throws IOException {
		out.writeChar('T');
		out.writeDouble(component.getPos().x);
		out.writeDouble(component.getPos().y);
		out.writeDouble(component.getPos().z);
		out.writeDouble(component.getOrientation().getY());
		out.writeDouble(component.getOrientation().getZ());
		out.writeChar(component.isLocked() ? 'L' : '.');
		out.writeChar(component.isRoot() ? 'R' : '.');
	}

	private void writeBall(Ball component) throws IOException {
		out.writeChar('B');
		out.writeDouble(component.getPos().x);
		out.writeDouble(component.getPos().y);
		out.writeDouble(component.getPos().z);
		out.writeChar(component.isLocked() ? 'L' : '.');
		out.writeChar(component.isRoot() ? 'R' : '.');
	}

}
